#include "lcd.h"
#include <util/delay.h>


void lcd_off()
{
//	C_RS;
	lcd_write ( 0x28 );		// lcd 4 bit, 2 lines, 5x7 dots
	lcd_write ( 0x0b );		// lcd off
}

void lcd_on()
{
	/// b1010xx
	C_RS;
	lcd_write ( 0x28 );		// lcd 4 bit, 2 lines, 5x7 dots
//	lcd_write ( 0x0f );		// lcd on, cur on, blinkin on
	lcd_write ( 0x0c );		// lcd on, cur off, blinkin on
}

void lcd_setio()
{

	C_ENA;
	C_RS;
	C_D0;
	C_D1;
	C_D2;
	C_D3;

	_DDR_RS		|= (1 << RS);
	_DDR_ENA	|= (1 << ENA);
	
	_DDR_D0		|= (1 << D0);
	_DDR_D1		|= (1 << D1);
	_DDR_D2		|= (1 << D2);
	_DDR_D3		|= (1 << D3);
	

}

void lcd_init()
{
	lcd_setio();
	C_RS;
	S_D0;
	S_D1;
	lcd_strobe();		// first write as 8bit
	_delay_ms ( 6 );
	lcd_strobe();		// first write as 8bit
	_delay_us ( 64 );
	lcd_strobe();		// first write as 8bit
	_delay_us ( 64 );

	C_D0;
	S_D1;
	C_D2;
	C_D3;

	lcd_strobe();

	lcd_on();
	lcd_clear();


}

//void lcd_reset()
//{
//	for (u8 c = 0; c < 16; c++)
//	{
//		lcd_write(

void lcd_strobe()
{
	S_ENA;
	lcd_wait;
	C_ENA;
	lcd_wait;
}


void lcd_write ( unsigned char bus )
{

	if ( ( ( bus & 0x10 ) >> 4 ) )
	{
		S_D0;
	}
	else
	{
		C_D0;
	}

	if ( ( ( bus & 0x20 ) >> 5 ) )
	{
		S_D1;
	}
	else
	{
		C_D1;
	}

	if ( ( ( bus & 0x40 ) >> 6 ) )
	{
		S_D2;
	}
	else
	{
		C_D2;
	}

	if ( ( ( bus & 0x80 ) >> 7 ) )
	{
		S_D3;
	}
	else
	{
		C_D3;
	}


	lcd_strobe();


	if ( ( ( bus & 0x01 ) ) )
	{
		S_D0;
	}
	else
	{
		C_D0;
	}

	if ( ( ( bus & 0x02 ) >> 1 ) )
	{
		S_D1;
	}
	else
	{
		C_D1;
	}

	if ( ( ( bus & 0x04 ) >> 2 ) )
	{
		S_D2;
	}
	else
	{
		C_D2;
	}

	if ( ( ( bus & 0x08 ) >> 3 ) )
	{
		S_D3;
	}
	else
	{
		C_D3;
	}

	lcd_strobe();
}


void  lcd_clear()
{
	C_RS;
	lcd_write ( 0x01 );
	lcd_wait;
	_delay_ms(3);
}

void  lcd_home()
{

	C_RS;

	lcd_write ( 0x02 );
	lcd_wait;
	_delay_ms(3);

}


void lcd_setpos ( unsigned char pos )
{

	if ( pos < 8 )
	{
		pos += 0x80;
	}
	else
	{
		pos += 0xC0 - 8;
	}
	C_RS;
	lcd_write ( pos );
}

void lcd_sign ( unsigned char sign )
{
	S_RS;
	lcd_write ( sign );
}


void lcd_print ( char *text )
{
	volatile unsigned char c;
	volatile unsigned char len = strlen ( text );

	S_RS;
	for ( c = 0; c < len; c++ )
	{
		lcd_write ( (char)*text );
		text++;
	}
	C_RS;
	_delay_ms(4);
}


void lcd_def(u8 num, u8 a, u8 b, u8 c, u8 d, u8 e, u8 f, u8 g, u8 h)
{
		C_RS;
		lcd_write(0x40 + num * 8);
		S_RS;
		lcd_write(a);
		lcd_write(b);
		lcd_write(c);
		lcd_write(d);
		lcd_write(e);
		lcd_write(f);
		lcd_write(g);
		lcd_write(h);

}

void lcd_def2(u8 num, char *tab)
{
	C_RS;
	lcd_write(0x40 + num * 8);
	S_RS;
	for (u8 c = 0; c < 8; c++)
	lcd_write(tab[c]);
}